from . import api
from flask import jsonify
from flask import request
from sqlalchemy import or_
from datetime import datetime

from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user

from .. import db
from ..models import DeviceInfo

@api.route('/device', methods=['POST'])
@login_required
def new_device():
    """
    创建新设备
    """
    response_data = request.json
    
    errmsg = ''
    device_info = DeviceInfo()
    try:
        device_info.device_name = response_data['device_name'].strip()
        if len(device_info.device_name) == 0:
            raise Exception('设备名称不能为空')
        device_info.device_type = response_data['device_type']
        device_info.server_ip = response_data['server_ip']
        if len(device_info.device_name) == 0:
            raise Exception('设备ip不能为空')
        device_info.server_port = response_data['server_port']
        device_info.device_username = response_data['device_username']
        device_info.device_password = response_data['device_password']
        device_info.device_url_suffix = response_data['device_url_suffix']

        db.session.add(device_info)
        db.session.commit()
    except Exception as e:
        errmsg = str(e)
    
    if device_info.id is None:
        return jsonify({'errcode': 500, 'errmsg': errmsg}), 500    
    else:
        return jsonify({'errcode': 0, 'errmsg': '', 'device_id': device_info.id}), 200
    


from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
@api.route('/devices', methods=['GET'])
@login_required
def get_devices():
    """
    获取成员列表
    """
    devices = DeviceInfo.query.all()
    import orjson
    return orjson.dumps(devices)


@api.route('/device/<device_id>/delete', methods=['POST'])
@login_required
def delete_device_info(device_id):
    """
    下发成员特征值
    """
    device_info = DeviceInfo.query.filter_by(id=device_id).first()
    
    errmsg = ''
    try:
        db.session.delete(device_info)
        db.session.commit()
    except Exception as e:
        errmsg = str(e)
        return jsonify({'errcode': 500, 'errmsg': errmsg}), 500 
    
    return jsonify({'errcode': 0, 'errmsg': '', 'device_id': device_id}), 200



@api.route('/device/<device_id>/issue', methods=['GET'])
@login_required
def issue_device_info(device_id):
    """
    下发成员特征值
    """
    device_info = DeviceInfo.query.filter_by(id=device_id).first()
    
    import urllib3
    data = {
        "device_id": device_info.id,
        "device_name": device_info.device_name,
        "device_type": device_info.device_type,
        "rtsp_url": device_info.get_rtsp_url()
            }
    
    http = urllib3.PoolManager()
    from flask import current_app
    url = current_app.config["CORE_API_URL"] + "/device_info"
    import json
    encoded_data = json.dumps(data)

    print(f"{url}")
    response = http.request(method='POST',
                            url=url,
                            body=encoded_data)
    # logger.debug(response.data)
    response_data = json.loads(response.data.decode())
    print(response_data)
    
    if response.status == 200 and int(response_data.get('errcode')) == 0:
        return jsonify({'errcode': 0, 'errmsg': "success"}), 200    
    else:
        return jsonify({'errcode': 10000, 'errmsg': 'unknown'}), 200
